package org.noidler.codex;

import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.InsertManyResult;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.bson.conversions.Bson;
import org.noidler.model.AnyThing;
import org.noidler.demo.AnythingBuilder;
import org.noidler.model.User;

import java.util.*;
import java.util.stream.Collectors;

public class MongoDb {
    public static void main(String[] args) {
        MongoDbClient mongoDbClient = new MongoDbClient();
        MongoDbCollection<AnyThing> anyCollection = new MongoDbCollection<>(mongoDbClient, "any", "base", AnyThing.class);

        InsertManyResult insertManyResult = anyCollection.insertMany(generateAlarms(10));
        List<String> ids = insertManyResult.getInsertedIds().values().stream()
                .map(BsonValue::asString)
                .map(BsonString::getValue)
                .collect(Collectors.toList());

        Bson filters = Filters.in("_id", ids);
        try (MongoCursor<AnyThing> cursor = anyCollection.find(filters).batchSize(ids.size()).cursor()) {
            while (cursor.hasNext()) {
                System.out.println("==================================!");
                AnyThing anyThing = cursor.next();
                System.out.println(anyThing);
            }
        }
        MongoDbCollection<User> userCollection = new MongoDbCollection<>(mongoDbClient, "controller", "users", User.class);

        String value = userCollection.insertOne(new User("user1", "user1")).getInsertedId().asObjectId().getValue().toString();
        System.out.println(value);
        mongoDbClient.close();
    }

    private static List<AnyThing> generateAlarms(int count) {
        List<AnyThing> alarms = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            alarms.add(gen());
        }
        return alarms;
    }

    public static AnyThing gen() {
        AnythingBuilder builder = AnythingBuilder.builder();
        UUID uuid = UUID.randomUUID();
        Map<String, Object> params = new HashMap<>();
        params.put("param1", "value1");
        params.put("param2", "value2");
        return builder.withCode(uuid.toString())
                .withId(uuid.toString())
                .withConditionType("condi" + uuid.toString())
                .withDescription("description" + uuid.toString())
                .withParams(params).build();
    }
}




